<!DOCTYPE html>
<html lang="zh-cn" color-mode="light">

  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="keywords" content="" />
  <meta name="author" content="郁涛丶" />
  <meta name="description" content="" />
  
  
  <title>
    
      Python__request，socket模块 
      
      
      |
    
     郁涛丶&#39;s Blog
  </title>

  
    <link rel="apple-touch-icon" href="/images/favicon.png">
    <link rel="icon" href="/images/favicon.png">
  

  <!-- Raleway-Font -->
  <link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">

  <!-- hexo site css -->
  
<link rel="stylesheet" href="/css/color-scheme.css">
<link rel="stylesheet" href="/css/base.css">
<link rel="stylesheet" href="//at.alicdn.com/t/font_1886449_67xjft27j1l.css">
<link rel="stylesheet" href="/css/github-markdown.css">
<link rel="stylesheet" href="/css/highlight.css">
<link rel="stylesheet" href="/css/comments.css">

  <!-- 代码块风格 -->
  
    
<link rel="stylesheet" href="/css/figcaption/mac-block.css">

  

  <!-- jquery3.3.1 -->
  
    <script defer type="text/javascript" src="/plugins/jquery.min.js"></script>
  

  <!-- fancybox -->
  
    <link href="/plugins/jquery.fancybox.min.css" rel="stylesheet">
    <script defer type="text/javascript" src="/plugins/jquery.fancybox.min.js"></script>
  
  
<script src="/js/fancybox.js"></script>


  

  <script>
    var html = document.documentElement
    const colorMode = localStorage.getItem('color-mode')
    if (colorMode) {
      document.documentElement.setAttribute('color-mode', colorMode)
    }
  </script>
<!-- hexo injector head_end start -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.min.css">

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hexo-math@4.0.0/dist/style.css">
<!-- hexo injector head_end end --><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="郁涛丶's Blog" type="application/atom+xml">
</head>


  <body>
    <div id="app">
      <div class="header">
  <div class="avatar">
    <a href="/">
      <!-- 头像取消懒加载，添加no-lazy -->
      
        <img src="/images/avatar.png" alt="">
      
    </a>
    <div class="nickname"><a href="/">Ghostasky</a></div>
  </div>
  <div class="navbar">
    <ul>
      
        <li class="nav-item" data-path="/">
          <a href="/">Home</a>
        </li>
      
        <li class="nav-item" data-path="/archives/">
          <a href="/archives/">Archives</a>
        </li>
      
        <li class="nav-item" data-path="/categories/">
          <a href="/categories/">Categories</a>
        </li>
      
        <li class="nav-item" data-path="/tags/">
          <a href="/tags/">Tags</a>
        </li>
      
        <li class="nav-item" data-path="/about/">
          <a href="/about/">About</a>
        </li>
      
    </ul>
  </div>
</div>


<script src="/js/activeNav.js"></script>



      <div class="flex-container">
        <!-- 文章详情页，展示文章具体内容，url形式：https://yoursite/文章标题/ -->
<!-- 同时为「标签tag」，「朋友friend」，「分类categories」，「关于about」页面的承载页面，具体展示取决于page.type -->


    <!-- LaTex Display -->

  
    <script async type="text/javascript" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
  
  <script>
    MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']]
      }
    }
  </script>


        
            
                <!-- clipboard -->

  
    <script async type="text/javascript" src="/plugins/clipboard.min.js"></script>
  
  
<script src="/js/codeCopy.js"></script>



                    
                        
                                
                                        
                                                
                                                        
                                                            <!-- 文章内容页 url形式：https://yoursite/文章标题/ -->
                                                            <div class="container post-details" id="post-details">
                                                                <div class="post-content">
                                                                    <div class="post-title">
                                                                        Python__request，socket模块
                                                                    </div>
                                                                    <div class="post-attach">
                                                                        <span class="post-pubtime">
        <i class="iconfont icon-updatetime" title="Update time"></i>
        2020-11-23
      </span>

                                                                        <span class="post-pubtime"> 本文共1.3k字 </span>

                                                                        <span class="post-pubtime">
        大约需要8min
      </span>

                                                                        
                                                                                    <span class="post-categories">
        <i class="iconfont icon-bookmark" title="Categories"></i>
        
        <span class="span--category">
          <a href="/categories/Technology/" title="Technology">
            <b>#</b> Technology
          </a>
        </span>
                                                                                    
                                                                                        </span>
                                                                                        
                                                                            <span class="post-tags">
        <i class="iconfont icon-tags" title="Tags"></i>
        
        <span class="span--tag">
          <a href="/tags/Python/" title="Python">
            <b>#</b> Python
          </a>
        </span>
                                                                            
                                                                                </span>
                                                                                
                                                                    </div>
                                                                    <div class="markdown-body">
                                                                        <p>[TOC]</p>
<hr>
<h1 id="一、requests库基本使用"><a href="#一、requests库基本使用" class="headerlink" title="一、requests库基本使用"></a>一、requests库基本使用</h1><p>请求方式：</p>
<p>​	get，post，head，put，delete，options。</p>
<p>**kwargs访问控制参数：</p>
<ul>
<li>params：字典或字节序列，作为参数加到URL中</li>
<li>data：字典、字节序列或文件对象，作为request的内容</li>
<li>json：json格式的数据，作为request的内容</li>
<li>headers：字典，http定制头</li>
<li>cookies：字典或cookiejar</li>
<li>files：字典类型，传输文件</li>
<li>timeout：设定超时时间，秒为单位、</li>
<li>proxies：字典类型，设定访问代理服务器，可以增加登陆认证</li>
<li>allow_redirects：true&#x2F;false，默认true，重定向开关</li>
<li>stream：true&#x2F;false，默认true，获取内容立即下载开关</li>
<li>verify：true&#x2F;false，默认true，认证SSL证书开关</li>
<li>cert：本地SSL证书</li>
<li>auth：元组，支持http认证功能</li>
</ul>
<p>使用requests方法后，会返回一个response对象。</p>
<p>response对象的属性：</p>
<blockquote>
<p>r.status_code：http请求的返回状态</p>
<p>r.text：http响应内容的字符串形式</p>
<p>r.encoding：从http header中猜测的响应内容编码方式</p>
<p>r.apparent_encodign：从内容中分析出的响应内容编码格式</p>
<p>r.content：http响应内容的二进制形式</p>
</blockquote>
<p>requests库的异常：</p>
<blockquote>
<p>requests.ConnectionError：网络连接错误异常，如DNS查询失败、拒绝连接等</p>
<p>requests.HTTPErroe：http错误异常</p>
<p>requests.URLRequired：URL缺失异常</p>
<p>requests.TooManyRedirects：超过最大重定向次数，产生重定向异常</p>
<p>requests.ConnectTimeout：连接远程服务器超时异常</p>
<p>requests.Timeyout请求URL是，产生超时异常</p>
<p>requests.raise_for_status()：如果不是200，产生requests.HTTPError</p>
</blockquote>
<h2 id="1-request-get-url-params-x3D-kwargs"><a href="#1-request-get-url-params-x3D-kwargs" class="headerlink" title="1.request.get(url,params&#x3D;*,**kwargs)"></a>1.request.get(url,params&#x3D;*,**kwargs)</h2><p>其中后两个参数可选</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> requests</span><br><span class="line">response = requests.get(<span class="string">&#x27;http://xxxx.xx&#x27;</span>)</span><br><span class="line"></span><br><span class="line">response = requests.get(<span class="string">&#x27;http://xxxx.xx/?a=xxx&amp;b=sss&#x27;</span>)</span><br><span class="line"></span><br><span class="line">data = &#123;<span class="string">&#x27;a&#x27;</span>=<span class="string">&#x27;xxx&#x27;</span>,<span class="string">&#x27;b&#x27;</span>=<span class="string">&#x27;sss&#x27;</span>&#125;</span><br><span class="line">response = requests.get(<span class="string">&#x27;http://xxxx.xx&#x27;</span>,params=data)</span><br><span class="line"></span><br><span class="line">payload = &#123;<span class="string">&#x27;key1&#x27;</span>: <span class="string">&#x27;value1&#x27;</span>, <span class="string">&#x27;key2&#x27;</span>: <span class="string">&#x27;value2&#x27;</span>&#125;</span><br><span class="line">headers = &#123;<span class="string">&#x27;content-type&#x27;</span>: <span class="string">&#x27;application/json&#x27;</span>&#125;</span><br><span class="line">response = requests.get(<span class="string">&quot;http://xxx.xx&quot;</span>, params=payload, headers=headers)</span><br><span class="line"></span><br><span class="line"><span class="comment">#response的一些属性：</span></span><br><span class="line"></span><br><span class="line">r = requests.get(<span class="string">&quot;https://www.baidu.com&quot;</span>)</span><br><span class="line"><span class="built_in">print</span> r.status_code</span><br><span class="line"><span class="comment">#print r.text</span></span><br><span class="line"><span class="built_in">print</span> r.encoding</span><br><span class="line"><span class="built_in">print</span> r.apparent_encoding</span><br><span class="line"><span class="comment">#print r.content</span></span><br><span class="line"><span class="comment">#print r.json()</span></span><br><span class="line"><span class="built_in">print</span> r.reason</span><br><span class="line"><span class="built_in">print</span> r.headers</span><br><span class="line"><span class="built_in">print</span> r.cookies</span><br><span class="line"><span class="built_in">print</span> r.raw</span><br></pre></td></tr></table></figure>

<h2 id="2-requests-post-url-data-x3D-None-json-x3D-None-kwargs"><a href="#2-requests-post-url-data-x3D-None-json-x3D-None-kwargs" class="headerlink" title="2.requests.post(url,data&#x3D;None,json&#x3D;None,**kwargs)"></a>2.requests.post(url,data&#x3D;None,json&#x3D;None,**kwargs)</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">import requests</span><br><span class="line">data=&#123;&#x27;a&#x27;=&#x27;xxx&#x27;,&#x27;b&#x27;=&#x27;sss&#x27;&#125;</span><br><span class="line">response = requests.post(&#x27;http://xxx.xx&#x27;,data=data)</span><br><span class="line"></span><br><span class="line">url = &#x27;http://httpbin.org/post&#x27;</span><br><span class="line">files = &#123;&#x27;file&#x27;: open(&#x27;test.txt&#x27;, &#x27;rb&#x27;)&#125;</span><br><span class="line">r = requests.post(url, files=files)</span><br><span class="line">print r.text</span><br></pre></td></tr></table></figure>
<h2 id="3-request-head-url-kwargs"><a href="#3-request-head-url-kwargs" class="headerlink" title="3.request.head(url,**kwargs)"></a>3.request.head(url,**kwargs)</h2><h2 id="4-requests-put-url-data-x3D-None-kwargs"><a href="#4-requests-put-url-data-x3D-None-kwargs" class="headerlink" title="4.requests.put(url,data&#x3D;None,**kwargs)"></a>4.requests.put(url,data&#x3D;None,**kwargs)</h2><h2 id="5-request-patch-url-data-x3D-None-kwargs"><a href="#5-request-patch-url-data-x3D-None-kwargs" class="headerlink" title="5.request.patch(url,data&#x3D;None,**kwargs)"></a>5.request.patch(url,data&#x3D;None,**kwargs)</h2><h2 id="6-request-delete-url-kwargs"><a href="#6-request-delete-url-kwargs" class="headerlink" title="6.request.delete(url,**kwargs)"></a>6.request.delete(url,**kwargs)</h2><p>以上都大同小异，就不写了。。。</p>
<h1 id="二、socket库"><a href="#二、socket库" class="headerlink" title="二、socket库"></a>二、socket库</h1><ul>
<li><p>sk.socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)</p>
<p>参数一：</p>
<p>​	默认为socket.AF_INET(IPv4)，还有socket.AF_INET6(IPv6),socket.AF_UNIX，其中最后一个只能用于单一的UNIX系统进程间通信</p>
<p>参数二：类型</p>
<p>​	socket.SOCK_STREAM  &#x2F;&#x2F;流式socket，tcp（默认）</p>
<p>​	socket.SOCK_DREAM  &#x2F;&#x2F;数据报式socket，udp</p>
<p>参数三：协议</p>
<p>​	（默认）与特定的地址家族相关的协议,如果是 0 ，则系统就会根据地址格式和套接类别,自动选择一个合适的协议(非必填)</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">#创建socket：</span><br><span class="line">    #TCP socket</span><br><span class="line">    sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)</span><br><span class="line">    # UDP socke</span><br><span class="line">    sk = socket.socket(socket.AF_INET,socket.SOCK_DREAM)</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="1-socket常用函数介绍"><a href="#1-socket常用函数介绍" class="headerlink" title="1.socket常用函数介绍"></a>1.socket常用函数介绍</h2><pre><code>  因为TCP发送数据时已经建立好链接，所以不需要指定地，UDP是面向无链接的，每次发送需要指定。
</code></pre>
<ul>
<li><h3 id="服务器端函数："><a href="#服务器端函数：" class="headerlink" title="服务器端函数："></a>服务器端函数：</h3><table>
<thead>
<tr>
<th>函数名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>sk.bind(address)</td>
<td>将套接字绑定到地址，address是元组(host,port)</td>
</tr>
<tr>
<td>sk.listen(backlog)</td>
<td>开始监听TCP传入链接，backlog指定在拒绝连接前，操作系统可以连接的最大连接数，最少为1</td>
</tr>
<tr>
<td>sk.accept()</td>
<td>接收TCP连接并返回(conn,address)，其中conn是新的套接字对象</td>
</tr>
</tbody></table>
</li>
<li><h3 id="客户端函数："><a href="#客户端函数：" class="headerlink" title="客户端函数："></a>客户端函数：</h3><table>
<thead>
<tr>
<th>函数名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>sk.connect(address)</td>
<td>连接到address处的套接字，address是元组(host,port)，如果连接出错，返回socket.error</td>
</tr>
<tr>
<td>sk.connect_ex(address)</td>
<td>功能与上相同，但成功返回0，失败返回erron的值</td>
</tr>
</tbody></table>
</li>
<li><h3 id="公共函数："><a href="#公共函数：" class="headerlink" title="公共函数："></a>公共函数：</h3><table>
<thead>
<tr>
<th>函数</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>sk.recv(bufsize[,flag])</td>
<td>接收TCP套接字的数据，数据已字符串形式返回，bufsize指定接收最大数据量，flag提供有关消息的其他信息，可省略</td>
</tr>
<tr>
<td>sk.send(string[,flag])</td>
<td>发送TCP数据，返回值是要发送的字节数量</td>
</tr>
<tr>
<td>sk.sendall(string[,flag])</td>
<td>发送完整TCP数据，在返回之前尝试发送所有数据，成功返回none，失败跑出异常</td>
</tr>
<tr>
<td>sk.recvfro(bufsize[,flag])</td>
<td>接收UDP套接字数据，返回值是(data,address)。data是包含接收数据的字符串，address是发送数据的套接字地址</td>
</tr>
<tr>
<td>sk.sendto(string[,flag],address)</td>
<td>发送UDP数据，address是元组(host,port)，返回值是发送的字节数</td>
</tr>
<tr>
<td>sk.close()</td>
<td>关闭套接字</td>
</tr>
<tr>
<td>sk.getpeername()</td>
<td>返回套接字的远程地址，返回值是(host,port)</td>
</tr>
<tr>
<td>sk.getsockname()</td>
<td>返回套接字自己的地址</td>
</tr>
</tbody></table>
</li>
</ul>
<h2 id="2-举例："><a href="#2-举例：" class="headerlink" title="2.举例："></a>2.举例：</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#服务器端</span></span><br><span class="line"><span class="keyword">import</span> socket</span><br><span class="line">host = <span class="string">&#x27;192.168.1.123&#x27;</span></span><br><span class="line">port = <span class="number">4444</span></span><br><span class="line">sk = socket.socket(socket.AF_INET,socket_STREAM)</span><br><span class="line">sk.bind((host,port))</span><br><span class="line">sk.listen(<span class="number">5</span>)</span><br><span class="line"><span class="built_in">print</span> <span class="string">&#x27;Conn...&#x27;</span></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&#x27;conn ok&#x27;</span></span><br><span class="line">    conn,addr = accept()</span><br><span class="line">    <span class="built_in">print</span> <span class="string">&#x27;conne form &#x27;</span>,addr</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">        data = sk.soket.recv(<span class="number">1024</span>)</span><br><span class="line">        <span class="built_in">print</span> data</span><br><span class="line">        <span class="built_in">print</span> <span class="string">&#x27;server received your msg&#x27;</span></span><br><span class="line">sk.close()</span><br><span class="line"></span><br><span class="line"><span class="comment">#客户端</span></span><br><span class="line"><span class="keyword">import</span> socket</span><br><span class="line">host = <span class="string">&#x27;192.168.1.123&#x27;</span></span><br><span class="line">port = <span class="number">4444</span></span><br><span class="line">sk = socket.socket(socket.AF_INET,socket,STREAM)</span><br><span class="line">sk.connet((host,port))</span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    msg = <span class="built_in">input</span>(<span class="string">&#x27;input msg:&#x27;</span>)</span><br><span class="line">    sk.send(msg)</span><br><span class="line">    data = sk.recv(<span class="number">1024</span>)</span><br><span class="line">    <span class="built_in">print</span> data</span><br><span class="line">sk.close()</span><br></pre></td></tr></table></figure>

<p>查看socket状态： <code>netstart -an</code></p>
<blockquote>
<p>request和socket大致介绍就这样了，不是很全，但基本用法都在这了</p>
</blockquote>

                                                                    </div>
                                                                    
                                                                        <div class="prev-or-next">
                                                                            <div class="post-foot-next">
                                                                                
                                                                                    <a href="/2020/11/22/BUU-RE-1/" target="_self">
                                                                                        <i class="iconfont icon-chevronleft"></i>
                                                                                        <span>Prev</span>
                                                                                    </a>
                                                                                    
                                                                            </div>
                                                                            <div class="post-attach">
                                                                                <!-- <span class="post-pubtime">
              <i class="iconfont icon-updatetime" title="Update time"></i>
              2020-11-23
            </span> -->

                                                                                
                                                                                            <span class="post-categories">
          <!-- <i class="iconfont icon-bookmark" title="Categories"></i> -->
          
          <!-- <span class="span--category">
            <a href="/categories/Technology/" title="Technology">
              <b>#</b> Technology
            </a>
          </span> -->
                                                                                            
                                                                                                </span>
                                                                                                
                                                                                    <span class="post-tags">
          <!-- <i class="iconfont icon-tags" title="Tags"></i> -->
          
          <!-- <span class="span--tag">
            <a href="/tags/Python/" title="Python">
              <b>#</b> Python
            </a>
          </span> -->
                                                                                    
                                                                                        </span>
                                                                                        
                                                                            </div>
                                                                            <div class="post-foot-prev">
                                                                                
                                                                                    <a href="/2020/11/25/%E6%96%87%E4%BB%B6%E5%8C%85%E5%90%AB%E6%BC%8F%E6%B4%9E/" target="_self">
                                                                                        <span>Next</span>
                                                                                        <i class="iconfont icon-chevronright"></i>
                                                                                    </a>
                                                                                    
                                                                            </div>
                                                                        </div>
                                                                        
                                                                </div>
                                                                
  <div id="btn-catalog" class="btn-catalog">
    <i class="iconfont icon-catalog"></i>
  </div>
  <div class="post-catalog hidden" id="catalog">
    <div class="title">Contents</div>
    <div class="catalog-content">
      
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81requests%E5%BA%93%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="toc-text">一、requests库基本使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-request-get-url-params-x3D-kwargs"><span class="toc-text">1.request.get(url,params&#x3D;*,**kwargs)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-requests-post-url-data-x3D-None-json-x3D-None-kwargs"><span class="toc-text">2.requests.post(url,data&#x3D;None,json&#x3D;None,**kwargs)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-request-head-url-kwargs"><span class="toc-text">3.request.head(url,**kwargs)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-requests-put-url-data-x3D-None-kwargs"><span class="toc-text">4.requests.put(url,data&#x3D;None,**kwargs)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-request-patch-url-data-x3D-None-kwargs"><span class="toc-text">5.request.patch(url,data&#x3D;None,**kwargs)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-request-delete-url-kwargs"><span class="toc-text">6.request.delete(url,**kwargs)</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81socket%E5%BA%93"><span class="toc-text">二、socket库</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-socket%E5%B8%B8%E7%94%A8%E5%87%BD%E6%95%B0%E4%BB%8B%E7%BB%8D"><span class="toc-text">1.socket常用函数介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="toc-text">服务器端函数：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="toc-text">客户端函数：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%AC%E5%85%B1%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="toc-text">公共函数：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E4%B8%BE%E4%BE%8B%EF%BC%9A"><span class="toc-text">2.举例：</span></a></li></ol></li></ol>
      
    </div>
  </div>

  
<script src="/js/catalog.js"></script>




                                                                    
                                                                        <div class="comments-container">
                                                                            







                                                                        </div>
                                                                        
                                                            </div>
                                                            
        
<div class="footer">
  <div class="social">
    <ul>
      
        <li>
          <a title="github" target="_blank" rel="noopener" href="https://github.com/Ghostasky">
            <i class="iconfont icon-github"></i>
          </a>
        </li>
      
        <li>
          <a title="twitter" target="_blank" rel="noopener" href="https://twitter.com/ghostasky">
            <i class="iconfont icon-twitter"></i>
          </a>
        </li>
      
    </ul>
  </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/Ghostasky">怕什么真理无穷，进一寸有进一寸的欢喜。</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Copyright © 2022 Oranges</a>
        
    </div>
  
    
    <div class="footer-more">
      
        <a target="_blank" rel="noopener" href="https://github.com/zchengsite/hexo-theme-oranges">Theme by Oranges | Powered by Hexo</a>
        
    </div>
  
</div>

      </div>

      <div class="tools-bar">
        <div class="back-to-top tools-bar-item hidden">
  <a href="javascript: void(0)">
    <i class="iconfont icon-chevronup"></i>
  </a>
</div>


<script src="/js/backtotop.js"></script>



        
  <div class="search-icon tools-bar-item" id="search-icon">
    <a href="javascript: void(0)">
      <i class="iconfont icon-search"></i>
    </a>
  </div>

  <div class="search-overlay hidden">
    <div class="search-content" tabindex="0">
      <div class="search-title">
        <span class="search-icon-input">
          <a href="javascript: void(0)">
            <i class="iconfont icon-search"></i>
          </a>
        </span>
        
          <input type="text" class="search-input" id="search-input" placeholder="Search...">
        
        <span class="search-close-icon" id="search-close-icon">
          <a href="javascript: void(0)">
            <i class="iconfont icon-close"></i>
          </a>
        </span>
      </div>
      <div class="search-result" id="search-result"></div>
    </div>
  </div>

  <script type="text/javascript">
    var inputArea = document.querySelector("#search-input")
    var searchOverlayArea = document.querySelector(".search-overlay")

    inputArea.onclick = function() {
      getSearchFile()
      this.onclick = null
    }

    inputArea.onkeydown = function() {
      if(event.keyCode == 13)
        return false
    }

    function openOrHideSearchContent() {
      let isHidden = searchOverlayArea.classList.contains('hidden')
      if (isHidden) {
        searchOverlayArea.classList.remove('hidden')
        document.body.classList.add('hidden')
        // inputArea.focus()
      } else {
        searchOverlayArea.classList.add('hidden')
        document.body.classList.remove('hidden')
      }
    }

    function blurSearchContent(e) {
      if (e.target === searchOverlayArea) {
        openOrHideSearchContent()
      }
    }

    document.querySelector("#search-icon").addEventListener("click", openOrHideSearchContent, false)
    document.querySelector("#search-close-icon").addEventListener("click", openOrHideSearchContent, false)
    searchOverlayArea.addEventListener("click", blurSearchContent, false)

    var searchFunc = function (path, search_id, content_id) {
      'use strict';
      var $input = document.getElementById(search_id);
      var $resultContent = document.getElementById(content_id);
      $resultContent.innerHTML = "<ul><span class='local-search-empty'>First search, index file loading, please wait...<span></ul>";
      $.ajax({
        // 0x01. load xml file
        url: path,
        dataType: "xml",
        success: function (xmlResponse) {
          // 0x02. parse xml file
          var datas = $("entry", xmlResponse).map(function () {
            return {
              title: $("title", this).text(),
              content: $("content", this).text(),
              url: $("url", this).text()
            };
          }).get();
          $resultContent.innerHTML = "";

          $input.addEventListener('input', function () {
            // 0x03. parse query to keywords list
            var str = '<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length <= 0) {
              return;
            }
            // 0x04. perform local searching
            datas.forEach(function (data) {
              var isMatch = true;
              var content_index = [];
              if (!data.title || data.title.trim() === '') {
                data.title = "Untitled";
              }
              var orig_data_title = data.title.trim();
              var data_title = orig_data_title.toLowerCase();
              var orig_data_content = data.content.trim().replace(/<[^>]+>/g, "");
              var data_content = orig_data_content.toLowerCase();
              var data_url = data.url;
              var index_title = -1;
              var index_content = -1;
              var first_occur = -1;
              // only match artiles with not empty contents
              if (data_content !== '') {
                keywords.forEach(function (keyword, i) {
                  index_title = data_title.indexOf(keyword);
                  index_content = data_content.indexOf(keyword);

                  if (index_title < 0 && index_content < 0) {
                    isMatch = false;
                  } else {
                    if (index_content < 0) {
                      index_content = 0;
                    }
                    if (i == 0) {
                      first_occur = index_content;
                    }
                    // content_index.push({index_content:index_content, keyword_len:keyword_len});
                  }
                });
              } else {
                isMatch = false;
              }
              // 0x05. show search results
              if (isMatch) {
                str += "<li><a href='" + data_url + "' class='search-result-title'>" + orig_data_title + "</a>";
                var content = orig_data_content;
                if (first_occur >= 0) {
                  // cut out 100 characters
                  var start = first_occur - 20;
                  var end = first_occur + 80;

                  if (start < 0) {
                    start = 0;
                  }

                  if (start == 0) {
                    end = 100;
                  }

                  if (end > content.length) {
                    end = content.length;
                  }

                  var match_content = content.substr(start, end);

                  // highlight all keywords
                  keywords.forEach(function (keyword) {
                    var regS = new RegExp(keyword, "gi");
                    match_content = match_content.replace(regS, "<span class=\"search-keyword\">" + keyword + "</span>");
                  });

                  str += "<p class=\"search-result-abstract\">" + match_content + "...</p>"
                }
                str += "</li>";
              }
            });
            str += "</ul>";
            if (str.indexOf('<li>') === -1) {
              return $resultContent.innerHTML = "<ul><span class='local-search-empty'>No result<span></ul>";
            }
            $resultContent.innerHTML = str;
          });
        },
        error: function(xhr, status, error) {
          $resultContent.innerHTML = ""
          if (xhr.status === 404) {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The search.xml file was not found, please refer to：<a href='https://github.com/zchengsite/hexo-theme-oranges#configuration' target='_black'>configuration</a><span></ul>";
          } else {
            $resultContent.innerHTML = "<ul><span class='local-search-empty'>The request failed, Try to refresh the page or try again later.<span></ul>";
          }
        }
      });
      $(document).on('click', '#search-close-icon', function() {
        $('#search-input').val('');
        $('#search-result').html('');
      });
    }

    var getSearchFile = function() {
        var path = "/search.xml";
        searchFunc(path, 'search-input', 'search-result');
    }
  </script>




        
  <div class="tools-bar-item theme-icon" id="switch-color-scheme">
    <a href="javascript: void(0)">
      <i id="theme-icon" class="iconfont icon-moon"></i>
    </a>
  </div>

  
<script src="/js/colorscheme.js"></script>





        
  
    <div class="share-icon tools-bar-item">
      <a href="javascript: void(0)" id="share-icon">
        <i class="iconfont iconshare"></i>
      </a>
      <div class="share-content hidden">
        
          <a class="share-item" href="https://twitter.com/intent/tweet?text=' + Python__request%EF%BC%8Csocket%E6%A8%A1%E5%9D%97 + '&url=' + https%3A%2F%2Fghostasky.github.io%2F2020%2F11%2F23%2Fpython__requestsocket%25E6%25A8%25A1%25E5%259D%2597%2F + '" target="_blank" title="Twitter">
            <i class="iconfont icon-twitter"></i>
          </a>
        
        
          <a class="share-item" href="https://www.facebook.com/sharer.php?u=https://ghostasky.github.io/2020/11/23/python__requestsocket%E6%A8%A1%E5%9D%97/" target="_blank" title="Facebook">
            <i class="iconfont icon-facebooksquare"></i>
          </a>
        
      </div>
    </div>
  
  
<script src="/js/shares.js"></script>



      </div>
    </div>
  </body>
</html>
